package cn.edu.fzu.homemaking.filter;

import java.io.IOException;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.fzu.homemaking.api.SsoApi;
import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.domain.entity.User;
import cn.edu.fzu.homemaking.util.ResultUtil;
import cn.edu.fzu.homemaking.web.Result;
import cn.edu.fzu.homemaking.web.RetCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

@WebFilter(urlPatterns = "/api/user/auth/*")
public class AuthFilter implements Filter {

    @Value("${index.url}")
    private String indexUrl;

    @Resource
    private SsoApi ssoApi;

    @Override
    public void init(FilterConfig filterConfig) {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        //判断是否登陆
        Result login = ssoApi.isLogin();
        if (login.getCode() != RetCode.SUCCESS) {
            //返回前端登陆报错信息，比如账号被异地登陆踢出
            respWriter(resp, new Result(RetCode.REFUSE_LOGIN, null, login.getMessage(), null));
            return;
        }
        //如果没有登陆
        if (!(boolean) login.getValue()) {

            //设置回调地址
            ssoApi.setSession(SessionConstant.REDIRECT_URL, indexUrl(session.getId()));

            //返回登陆页面给前端
            String loginUrl = (String) ssoApi.loginIndex(session.getId()).getValue();
            respWriter(resp, new Result(RetCode.NO_LOGIN, null, null, loginUrl));
            return;
        }
        //获取用户来源哪个端
        String origin = (String) ssoApi.getSession(SessionConstant.USER_TYPE).getValue();
        if (StringUtils.isBlank(origin)) {
            //设置用户来源为用户端
            origin = SessionConstant.USER;
            //如果来源未知，则告知sso，用户来源用户端
            ssoApi.setSession(SessionConstant.USER_TYPE, origin);
        }
        //告知本系统，用户来源于何处
        session.setAttribute(SessionConstant.USER_TYPE, origin);

        //如果用户来源于user端，则从sso获取用户信息
        if (Objects.equals(SessionConstant.USER, origin)) {
            //从sso的session中获取账号信息，进行反序列化为本项目的user对象，放入本项目的session中
            Result result = ssoApi.getSession(SessionConstant.ACCOUNT);
            User user = JSON.parseObject(((JSONObject) result.getValue()).toJSONString(), User.class);
            session.setAttribute(SessionConstant.ACCOUNT, user);
        }
        chain.doFilter(req, resp);
    }


    @Override
    public void destroy() {
        // do nothing
    }


    private void respWriter(HttpServletResponse resp, Result result) throws IOException {
        resp.getWriter().print(JSON.toJSONString(result));
    }


    private String indexUrl(String sessionId) {
        return indexUrl + "?" + SessionConstant.DSESSIONID + "=" + sessionId;
    }
}
